<template>
    <div class="question-generation-container">
        <!-- 出题配置区域 -->
        <div v-if="selectedKnowledge.length > 0" class="question-generation">
            <el-divider content-position="left">出题配置</el-divider>

            <div class="generation-config">
                <div class="config-row">
                    <div class="config-item">
                        <label class="config-label">题目类型:</label>
                        <el-select v-model="questionConfig.questionType" placeholder="请选择题目类型" style="width: 160px;">
                            <el-option v-for="type in questionTypes" :key="type.value" :label="type.label"
                                :value="type.value">
                            </el-option>
                        </el-select>
                    </div>

                    <div class="config-item">
                        <label class="config-label">题目难度:</label>
                        <el-select v-model="questionConfig.difficultyLevel" placeholder="请选择题目难度" style="width: 160px;">
                            <el-option v-for="level in difficultyLevels" :key="level.value" :label="level.label"
                                :value="level.value">
                            </el-option>
                        </el-select>
                    </div>
                </div>

                <div class="config-actions">
                    <el-button type="primary" @click="generateQuestion" :loading="isGenerating"
                        :disabled="!questionConfig.questionType || !questionConfig.difficultyLevel"
                        icon="el-icon-magic-stick">
                        {{ isGenerating ? '生成中...' : '生成题目' }}
                    </el-button>

                    <el-button v-if="generatedQuestion" type="success" @click="showQuestionPreview = true"
                        icon="el-icon-view">
                        预览题目
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 生成结果展示 -->
        <div v-if="generatedQuestion" class="question-result">
            <el-divider content-position="left">生成的题目</el-divider>
            <div class="result-summary">
                <el-tag type="info" size="small">{{ getQuestionTypeLabel(questionConfig.questionType) }}</el-tag>
                <el-tag type="warning" size="small" style="margin-left: 8px;">{{
                    getDifficultyLabel(questionConfig.difficultyLevel) }}</el-tag>
                <span style="margin-left: 12px; color: #666; font-size: 13px;">
                    基于 {{ selectedKnowledge.length }} 个知识点生成
                </span>
            </div>
        </div>

        <!-- 题目预览对话框 -->
        <el-dialog title="题目预览" :visible.sync="showQuestionPreview" width="80%" :close-on-click-modal="false">
            <QuestionDisplay v-if="generatedQuestion" :questions="generatedQuestion"
                :questionType="questionConfig.questionType" :questionConfig="questionConfig" :courseId="courseId"
                @edit-questions="handleEditQuestions" @preview-test="handlePreviewTest"
                @questions-updated="handleQuestionsUpdated" />

            <span slot="footer" class="dialog-footer">
                <el-button @click="showQuestionPreview = false">关闭</el-button>
                <el-button type="primary" @click="saveQuestion">保存题目</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
import QuestionDisplay from './QuestionDisplay.vue';
import { saveQuestionData } from '@/api/exam/exam';

export default {
    name: 'QuestionGeneration',
    components: {
        QuestionDisplay
    },
    props: {
        selectedKnowledge: {
            type: Array,
            default: () => []
        },
        courseId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            // 出题配置
            questionConfig: {
                questionType: '',
                difficultyLevel: ''
            },

            // 题目类型选项
            questionTypes: [
                { value: "choice", label: "单选题" },
                { value: "TF", label: "判断题" },
                { value: "fill", label: "填空题" },
                { value: "answer", label: "简答题" }
            ],

            // 难度级别选项
            difficultyLevels: [
                { value: "easy", label: "简单" },
                { value: "difficulty", label: "困难" }
            ],

            // 生成状态和结果
            isGenerating: false,
            generatedQuestion: null,
            showQuestionPreview: false
        }
    },
    methods: {
        // 生成题目
        async generateQuestion() {
            if (!this.questionConfig.questionType || !this.questionConfig.difficultyLevel) {
                this.$message.warning('请选择题目类型和难度');
                return;
            }

            if (this.selectedKnowledge.length === 0) {
                this.$message.warning('请先选择知识点');
                return;
            }

            this.isGenerating = true;

            try {
                // 准备请求数据
                const requestData = {
                    questionType: this.questionConfig.questionType,
                    difficultyLevel: this.questionConfig.difficultyLevel,
                    data: this.selectedKnowledge.map(item => ({
                        content: item.content || item.label,
                        summary: item.label
                    }))
                };

                console.log('出题请求数据:', requestData);

                // 调用出题接口
                const response = await this.callGenerateQuestionAPI(requestData);

                if (response) {
                    this.generatedQuestion = response;
                    this.$message.success('题目生成成功！');
                    console.log('生成的题目:', this.generatedQuestion);

                    // 触发事件，向父组件传递生成的题目
                    this.$emit('question-generated', {
                        config: this.questionConfig,
                        question: this.generatedQuestion,
                        knowledgePoints: this.selectedKnowledge
                    });
                } else {
                    this.$message.error('题目生成失败，请重试');
                }
            } catch (error) {
                console.error('生成题目出错:', error);
                this.$message.error(`生成题目失败: ${error.message || '未知错误'}`);
            } finally {
                this.isGenerating = false;
            }
        },

        // 调用题目生成API
        async callGenerateQuestionAPI(data) {
            try {
                const response = await axios.post('http://111.63.183.17:5000/generate_question', data, {
                    headers: {
                        'Content-Type': 'application/json'
                    },
                });

                return response.data;
            } catch (error) {
                if (error.response) {
                    // 服务器响应了错误状态码
                    throw new Error(`服务器错误: ${error.response.status} ${error.response.statusText}`);
                } else if (error.request) {
                    // 请求已发出但没有收到响应
                    throw new Error('网络错误，请检查网络连接');
                } else {
                    // 其他错误
                    throw new Error(error.message || '请求失败');
                }
            }
        },

        // 获取题目类型标签
        getQuestionTypeLabel(type) {
            const found = this.questionTypes.find(item => item.value === type);
            return found ? found.label : type;
        },

        // 获取难度标签
        getDifficultyLabel(level) {
            const found = this.difficultyLevels.find(item => item.value === level);
            return found ? found.label : level;
        },

        // 获取题目类型对应的标签类型
        getQuestionTypeTagType(type) {
            const typeMap = {
                'choice': 'primary',
                'TF': 'success',
                'fill': 'warning',
                'answer': 'info'
            };
            return typeMap[type] || 'info';
        },

        // 处理编辑题目事件
        handleEditQuestions(data) {
            console.log('编辑题目:', data);
            this.$emit('edit-questions', data);
            this.$message.info('编辑功能待开发');
        },

        // 处理题目更新事件
        handleQuestionsUpdated(updatedData) {
            console.log('题目已更新:', updatedData);

            // 检查传入的数据结构，如果是对象则提取questions数组
            let questionsArray;
            if (Array.isArray(updatedData)) {
                // 直接是数组
                questionsArray = updatedData;
            } else if (updatedData && updatedData.questions && Array.isArray(updatedData.questions)) {
                // 是包含questions属性的对象
                questionsArray = updatedData.questions;
            } else {
                console.error('题目更新数据格式错误:', updatedData);
                this.$message.error('题目更新数据格式错误');
                return;
            }

            // 更新本地的生成题目数据
            this.generatedQuestion = questionsArray;

            // 触发事件通知父组件题目已更新
            this.$emit('questions-updated', {
                config: this.questionConfig,
                questions: questionsArray,
                knowledgePoints: this.selectedKnowledge
            });
        },

        // 处理预览测试事件
        handlePreviewTest(data) {
            console.log('预览测试:', data);
            this.$emit('preview-test', data);
            this.$message.info('预览测试功能待开发');
        },

        // 保存题目
        async saveQuestion() {
            if (!this.generatedQuestion) {
                this.$message.warning('没有可保存的题目');
                return;
            }

            if (!this.courseId) {
                this.$message.warning('缺少课程ID，无法保存题目');
                return;
            }

            try {
                // 格式化题目数据
                const formattedData = this.formatQuestionsForAPI(this.generatedQuestion);
                console.log('格式化后的题目数据:', formattedData);

                // 调用保存API
                const response = await saveQuestionData(this.courseId, formattedData);

                this.$message.success('题目保存成功！');
                this.showQuestionPreview = false;

                // 触发保存事件
                this.$emit('question-saved', {
                    config: this.questionConfig,
                    question: this.generatedQuestion,
                    knowledgePoints: this.selectedKnowledge,
                    savedData: formattedData,
                    response: response
                });
            } catch (error) {
                console.error('保存题目失败:', error);
                const errorMessage = error.response && error.response.data && error.response.data.message
                    ? error.response.data.message
                    : error.message || '保存失败';
                this.$message.error(`保存题目失败: ${errorMessage}`);
            }
        },

        // 格式化题目数据为API所需格式
        formatQuestionsForAPI(questions) {
            if (!Array.isArray(questions)) {
                console.error('题目数据格式错误，应为数组:', questions);
                return [];
            }

            return questions.map(question => {
                // 映射题目类型: choice → choose, TF → judge
                const typeMapping = {
                    'choice': 'choose',
                    'TF': 'judge',
                    'fill': 'fill',
                    'answer': 'answer'
                };

                // 映射难度级别: easy → "1", difficulty → "2"
                const levelMapping = {
                    'easy': '1',
                    'difficulty': '2'
                };

                const mappedType = typeMapping[this.questionConfig.questionType] || this.questionConfig.questionType;
                const mappedLevel = levelMapping[this.questionConfig.difficultyLevel] || this.questionConfig.difficultyLevel;

                return {
                    quType: mappedType,
                    level: mappedLevel,
                    content: question
                };
            });
        }
    }
}
</script>

<style scoped>
.question-generation-container {
    width: 100%;
}

/* 出题配置区域样式 */
.question-generation {
    margin-top: 20px;
}

.generation-config {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 16px;
}

.config-row {
    display: flex;
    gap: 24px;
    margin-bottom: 16px;
    flex-wrap: wrap;
}

.config-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.config-label {
    font-weight: 500;
    color: #333;
    white-space: nowrap;
    min-width: 70px;
}

.config-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}

/* 题目结果区域样式 */
.question-result {
    margin-top: 20px;
}

.result-summary {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 6px;
    margin-bottom: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .config-row {
        flex-direction: column;
        gap: 12px;
    }

    .config-actions {
        flex-wrap: wrap;
    }
}
</style>
